﻿using System;
using System.Web.UI;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.Payment.Methods.Moneris;

namespace NopSolutions.NopCommerce.Web
{
    public partial class MonerisHostedPaymentReturn : BaseNopFrontendPage
    {
        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            Load += new EventHandler(MonerisHostedPaymentReturn_Load);
        }

        void MonerisHostedPaymentReturn_Load(object sender, EventArgs e) {
            //comment this line to process return
            Response.Redirect(CommonHelper.GetStoreLocation());

            if (NopContext.Current.User == null) {
                string loginURL = SEOHelper.GetLoginPageUrl(true);
                Response.Redirect(loginURL);
            }

            if (!Page.IsPostBack) {
                CommonHelper.SetResponseNoCache(Response);

                string rspCode = CommonHelper.QueryString("response_code");
                if (String.IsNullOrEmpty(rspCode) || rspCode.ToUpperInvariant().Equals("NULL") || CommonHelper.QueryStringInt("response_code") >= 50) {
                    Response.Redirect(CommonHelper.GetStoreLocation());
                }

                Guid? guid = CommonHelper.QueryStringGuid("order_no");
                if (!guid.HasValue) {
                    Response.Redirect(CommonHelper.GetStoreLocation());
                }
                Order order = this.OrderService.GetOrderByGuid(guid.Value);
                if (order == null) {
                    Response.Redirect(CommonHelper.GetStoreLocation());
                }
                if (NopContext.Current.User.CustomerId != order.CustomerId) {
                    Response.Redirect(CommonHelper.GetStoreLocation());
                }

                if (HostedPaymentSettings.AuthorizeOnly) {
                    if (this.OrderService.CanMarkOrderAsAuthorized(order)) {
                        this.OrderService.MarkAsAuthorized(order.OrderId);
                    }
                }
                else if (this.OrderService.CanMarkOrderAsPaid(order)) {
                    this.OrderService.MarkOrderAsPaid(order.OrderId);
                }
                Response.Redirect("~/checkoutcompleted.aspx");
            }
        }

        public override bool AllowGuestNavigation {
            get {
                return true;
            }
        }

        /// <summary>
        /// Gets a value indicating whether this page is tracked by 'Online Customers' module
        /// </summary>
        public override bool TrackedByOnlineCustomersModule {
            get {
                return false;
            }
        }
    }
}
